import request from '../../common/request'

import {xzl,wlq,hdb} from '../../common/config'

Page({
  data: {
    goodsObj: {},
    showBottom: true,
    content: "",
    goodsId: 0,
    // 评论列表
    contentList: [],


    // 是否被收藏
    isCollected:0,

    // 收藏的总数
    collectedNum:0,

    // 页数
    // 当前页数
    page: 1,

    // 每条页数
    size: 3,

    // 总留言数
    total:0,

    // 总页数
    pages: 0,
    // 卖家的id
    shopUserId: 0,

    // 父留言
    // pid解决子留言是属于哪条父留言的
    pid: null,
    // toid解决这条留言回复哪条子留言
    toid: null,

    toNickName:'',
    nickname:wx.getStorageSync('userInfo').nickName,

    // 在输入框显示的昵称
    showNickName:'',

    // 用户id
    userId:wx.getStorageSync('userId'),

    // 子评论的数目
    childrenContentNum:3,
  },

  onLoad: function (option) {
    console.log(option.goodsId);
    this.setData({
      goodsId: option.goodsId,
    });

    // 获取商品详情列表
    this.getGoodsDetail(option.goodsId);

    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  onShow() {
    // 获取商品评论列表
    this.getGoodsContent(this.data.goodsId);
  },

  // 获取商品详情页
  async getGoodsDetail(id) {
    console.log(id)
    const token = wx.getStorageSync('cookie');
    const URL = `${xzl}/getGoodsDetail/${id}?access_token=${token}`;
    const res = await request(URL);
    this.setData({
      goodsObj: res.data,
      // 商品卖家的id
      shopUserId: res.data.userId,
      isCollected:res.data.isCollected,
      collectedNum:res.data.collectedNum,
    });
  },

  // 处理输入文字框架
  handleTextarea(e) {
    // console.log(e.detail.value);
    this.setData({
      content: e.detail.value,
    });
  },
  // 切换评论输入框

  // 直接给卖家留言是不需要pid和toid
  handleContent() {
    this.setData({
      showBottom: false,
      pid: null,
      toid: null,
      toNickName:'',
      showNickName:'@卖家:'
    });
  },

  // 处理外面的评论
  handleOutContent(e) {
    console.log("处理外面的评论", e.currentTarget.dataset);
    this.setData({
      showBottom: false,
      pid: e.currentTarget.dataset.pid,
      toid: e.currentTarget.dataset.toid,
      toNickName:e.currentTarget.dataset.tonickname,
      showNickName:`@${e.currentTarget.dataset.shownickname}:`
    });
  },

  // 处理里面的评论
  handleInnerContent(e) {
    console.log("点击的是里面的评论", e.currentTarget.dataset);
    this.setData({
      showBottom: false,
      pid: e.currentTarget.dataset.pid,
      toid: e.currentTarget.dataset.toid,
      toNickName:e.currentTarget.dataset.tonickname,
      showNickName:`@${e.currentTarget.dataset.shownickname}:`
    });
  },

  // 取消按键退出输入框
  handleCancel() {
    this.setData({
      showBottom: true,
      content:''
    });
  },

  // 发布评论
  async publishMyContent(e) {
    console.log("发布评论");

    if (!wx.getStorageSync("isLogin")) {
      wx.showModal({
        title: "提示",
        content: "评论之前请先进行登录",
        showCancel: true,
        cancelText: "不了",
        cancelColor: "#000000",
        confirmText: "跳转授权",
        confirmColor: "#3CC51F",
        success: (result) => {
          if (result.confirm) {
            wx.switchTab({
              url: "/pages/user/user",
            });
          }
        },
        fail: (err) => {
          console.log("异常错误", err);
        },
      });
      return;
    }


    this.setData({
      showBottom: true,
    });

    let { pid, toid } = this.data;
    // 评论的信息
    let query = {
      userId: wx.getStorageSync("userId"),
      goodsId: this.data.goodsId,
      content: this.data.content,
      pid,
      toid,
    };

    const URL = `${wlq}/comment?access_token=${wx.getStorageSync( "cookie")}`;

    const res = await request(URL,'POST',query);

    if(res.code!==200){
      console.log('发布评论失败',res)
      return;
    }
    console.log("发布评论成功！！", res);
    wx.showToast({
      title: '评论成功',
      icon: 'success',
    })
    // 插入新数据
    let contentItem = {
      userInfo: {
        nickName: wx.getStorageSync("userInfo").nickName,
        avatarUrl: wx.getStorageSync("userInfo").avatarUrl,
      },
      content: this.data.content,
      createTime: (new Date()).toString(),
      userId: wx.getStorageSync("userId"),
      commentId:res.data,
      toNickName:this.data.toNickName
    };

    // 根据父id有没有值，id为空直接插在外面，当id不为空，则找到对应的id，然后插入孩子列表

    let  {contentList,total } = this.data;

    total++;

    if (pid === null) {
      // 给卖家留言
      contentList.unshift(contentItem);
      console.log('更新评论父留言',contentList)
    } else{ 
      contentList.map(item=>{
        if(item.commentId===pid){
          if(!item.children){
            item['children'] = [];
            item.children.unshift(contentItem)
          }else{
            item.children.unshift(contentItem)
          }
        }
      });
      console.log('更新的评论子留言------',contentList);
    }

    this.setData({
      contentList,
      content: "",
      total,
    });
  },

  // 获取商品评论
 async getGoodsContent(goodsId) {
    let { page, size } = this.data;
    const URL = `${wlq}/comment/${goodsId}/${page}/${size}`;
    const {data} = await request(URL);

    this.setData({
      // 但前页数
      page: data.current,
      // 总页数
      pages: data.pages,
      // 留言总数
      total:data.total,
      size:data.size,
      // 评论内容
      contentList: data.records,

    });

  },


  // 获取其他评论
  async getOtherContent(){

    let {goodsId,page,size,contentList} = this.data;
    page++;
    // 发送请求
    const URL = `${wlq}/comment/${goodsId}/${page}/${size}`;
    const {data} = await request(URL);
    contentList = [...contentList,...data.records];
    this.setData({
      page:data.current,
      pages:data.pages,
      contentList
    })

  },

  // 点击父留言得到全部子留言
  async getChildReply(e){

    const commentId = e.currentTarget.dataset.commentid;
    let {contentList} = this.data;
    // 发送请求，得到这一条父留言的全部子留言
    const URL = `${wlq}/comment/${commentId}`;
    const {data} = await request(URL);

    contentList.map(item=>{
      if(item.commentId===commentId){
        item.children= data.children;
      }
    })
    console.log('更新之后的子评论',contentList);
    this.setData({
     contentList,
     childrenContentNum:data.childrenSum
    })
  },

  // 删除评论
  async delContent(e){

    let {commentid,fathercommentid} = e.currentTarget.dataset;

    let {contentList} = this.data;
    const URL = `${wlq}/comment/${commentid}?access_token=${wx.getStorageSync('cookie')}`;
    const res = await request(URL,'DELETE');
    console.log('删除评论',res);
    // 如果fathercommentid存在的话，表明删除的是子留言
    wx.showToast({
      title: '删除评论成功',
      icon: 'success',
    });
    
    if(fathercommentid){
      contentList.map(item=>{
        if(item.commentId === fathercommentid){
          let index = item.children.findIndex(childrenItem=>childrenItem.commentId===commentid);
          item.children.splice(index,1);
        }
      })
    }else{
      let index = contentList.findIndex(item=>item.commentId==commentid);
      // 删除指定位置的数据
      contentList.splice(index,1);
    }

    this.setData({
      contentList
    })

  },

  // 处理转发分享功能
  onShareAppMessage:function(option){
    if(option.from === 'button'){
      // 来自页面内转发按钮
      console.log(option)
    }
    // 要传递参数过去。
    return{
      title:`${option.target.dataset.nickname}的好物分享`,
      path:`/pages/goods_detail/goods_detail?goodsId=${option.target.dataset.goodsid}`
    }

  },

  // 收藏
  likeGoods(){
    let {isCollected,collectedNum,goodsId} = this.data;
    const token = wx.getStorageSync('cookie');
      
    if(isCollected){
      // 取消收藏
      const URL = `${hdb}?access_token=${token}`;
      request(URL,'DELETE',JSON.stringify({goods_id:goodsId}));

      collectedNum--;
      this.setData({
        isCollected:0,
        collectedNum,
      })
    }else{
      const URL = `${hdb}?access_token=${token}`;
      request(URL,'POST',JSON.stringify({goods_id:goodsId}));
      collectedNum++;
      this.setData({
        collectedNum,
        isCollected:1,
      })
    }

  },


  // 跳转到私聊页面
  handleChat(e){
    // console.log('商品详情页跳转到聊天页面',e.currentTarget.dataset)
    const {userid,avatarurl,nickname} = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/socket/socket?userId=${userid}&&avatarUrl=${avatarurl}&&nickName=${nickname}`,
    });
  },


  // 跳转到订单页面
  navToOrder(e){
    // 跳转到订单页面，需要把商品id传过去
    console.log(e.currentTarget.dataset.userid)
    const {goodsId,userId} = this.data;
    if(e.currentTarget.dataset.userid === userId ){
      wx.showModal({
        title: '提示',
        content: '请不要给自己的商品下单！',
        showCancel: false,
        confirmText: '知道了',
        confirmColor: '#3CC51F',
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/order/order?goodsId=${goodsId}`,
    });
  },
  // 跳转到卖家主页
  navTosellerHome(e){
    const dataSet = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/sellerHome/sellerHome?userId=${dataSet.id}&avatarUrl=${dataSet.avatarurl}&nickName=${dataSet.nickname}`,
    });
  }
});
